<template>
  <div class="channel-jurisdiction">
    <el-container class="container-box">
      <el-header height="auto">
        <el-form inline :model="searchForm">
          <el-form-item label="角色名称">
            <el-input v-model="searchForm.roleName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.addDaterange"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchHandler">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-header>
      <el-editable
        :data="tableData"
        :columns="columns"
        v-loading="getListLoading"
        :custom-attr="$TABLE_HEAD['systemSetup.jurisdiction.list']"
        height="200"
      >
        <template slot="default-operation" slot-scope="scope">
          <el-button size="small" type="text" @click.stop="beforeEdit(scope)"
            >修改</el-button
          >
          <!-- <el-button size="small" type="text" @click.stop="getResourceTree(scope)" >设置</el-button> -->
          <el-button size="small" type="text" @click.stop="toSet(scope)"
            >设置</el-button
          >
          <el-button size="small" type="text" @click.stop="beforeDelete(scope)"
            >删除</el-button
          >
        </template>
      </el-editable>
      <!-- 分页功能 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
      <el-dialog
        title="角色管理——业务专用"
        :visible.sync="dialogTreeVisible"
        width="500px"
      >
        <el-tree
          ref="tree"
          v-loading="treeLoading"
          :data="treeData"
          show-checkbox
          default-expand-all
          node-key="appResourceId"
          :render-content="renderContent"
          :default-checked-keys="treeSelectKeys"
          :props="defaultProps"
        />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogTreeVisible = false">取 消</el-button>
          <el-button type="primary" @click="getSelected">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :title="editTitle"
        :visible.sync="dialogEditVisible"
        width="450px"
        @closed="resetEditForm"
        class="edit-form"
      >
        <el-form :model="editForm" label-position="right" label-width="80px">
          <el-form-item required label="角色名称">
            <el-input v-model="editForm.roleName" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              type="textarea"
              :rows="4"
              maxlength="200"
              v-model="editForm.roleDesc"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取 消</el-button>
          <el-button
            :loading="submitBtnLoading"
            type="primary"
            @click="editDialogHandler"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-container>
  </div>
</template>

<script>
import {columns} from './const'
import {formatDate, sliceMenuName} from '@const/filter.js'
import {PAGE_NUMBER, PAGINATION_LAYOUT} from '@const/common'
import {
  getMerchantRolePageList,
  getRoleResourceTreeByRoleId,
  roleDeleteById,
  merchantRoleSave,
  merchantRoleUpdate,
  roleSaveRoleResourceTree,
  getAppByCompanyId
} from '@const/api_staffCenter.js'
import ElEditable from '@components/el-editable'
import {mapState} from 'vuex'
import {getTargetValByKey, renderContent} from '@const/utils.js'
import {hasIn} from 'lodash'

export default {
  components: {ElEditable},
  data() {
    return {
      columns,
      renderContent,
      tableData: [],
      getListLoading: false,
      treeLoading: false,
      searchForm: {
        roleName: '',
        addDaterange: '',
        addStartTime: '',
        addEndTime: ''
      },
      editForm: {
        id: '',
        roleName: '',
        roleDesc: '',
        appId: ''
      },
      curPage: 1, // 当前页
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      pageSize: PAGE_NUMBER[0], // 一页的数量
      totalElements: 0,
      treeData: [],
      dialogTreeVisible: false,
      dialogEditVisible: false,
      isEdit: false,
      defaultProps: {
        children: 'children',
        label: 'appResourceName'
      },
      roleId: '',
      appId: '', // 权限设置时，子系统的id
      insertPermissionIds: [],
      permissionIds: [],
      defultPermissionIds: [], // 某角色默认的的资源ID
      addCompanyObj: null, // 记录新增的返回对象
      submitBtnLoading: false, // 弹层确定按钮loading
      treeSelectKeys: [],
      editTitle: '新增角色'
    }
  },
  computed: {
    ...mapState(['userId', 'roleType'])
  },
  mounted() {
    // 获取角色列表
    this.getRoleList()
    let obj = {
      type: 'btn',
      arr: [
        {
          val: '添加',
          type: 'primary',
          handle: this.beforeAdd
        }
      ]
    }
    this.$store.commit('changeLayoutHandle', obj)
  },
  methods: {
    getRoleList() {
      let {roleName, addStartTime, addEndTime} = this.searchForm
      this.getListLoading = true
      this.$axios
        .$get(
          `${getMerchantRolePageList}?page=${this.curPage}&pageSize=${this.pageSize}&createTimeEnd=${addEndTime}&createTimeStart=${addStartTime}&roleName=${roleName}`
        )
        .then(res => {
          let {content, totalElements} = res.payload
          this.tableData = content
          this.totalElements = totalElements
        })
        .finally(res => {
          this.getListLoading = false
        })
    },
    toSet(scope) {
      this.$router.push({
        path: '/systemSetup/jurisdiction/set',
        query: {
          id: scope.row.id
        }
      })
    },
    // 根据角色ID查询所拥有的资源
    getResourceTree(scope) {
      this.treeLoading = true
      this.dialogTreeVisible = true
      this.insertPermissionIds = []
      // 先reset
      let {appId, id} = scope.row
      // 设置子系统id，提交菜单的时候需要
      this.appId = appId
      this.roleId = id
      this.$axios({
        url: getRoleResourceTreeByRoleId,
        method: 'get',
        params: {appId, roleId: id}
      })
        .then(res => {
          let menuList = hasIn(res, ['data', 'payload']) ? res.data.payload : []
          this.treeData = menuList
          // 求资源树的所有id和角色所拥有的资源的资源的交集，勾选
          this.treeSelectKeys = getTargetValByKey(
            menuList,
            'selected',
            true,
            'appResourceId'
          )
        })
        .finally(res => {
          this.treeLoading = false
        })
    },
    searchHandler() {
      if (this.searchForm.addDaterange && this.searchForm.addDaterange.length) {
        ;[this.searchForm.addStartTime, this.searchForm.addEndTime] = [
          ...this.searchForm.addDaterange
        ]
      } else {
        this.searchForm.addStartTime = ''
        this.searchForm.addEndTime = ''
      }
      this.curPage = 1
      this.pageSize = 20
      this.getRoleList()
    },
    delHandler(scope) {
      this.getListLoading = true
      this.$axios({
        url: roleDeleteById,
        method: 'POST',
        data: {id: scope.row.id}
      })
        .then(res => {
          this.messageBox('删除成功！')
          this.resetForm()
          this.curPage = 1
          this.pageSize = 20
          this.getRoleList()
        })
        .finally(() => {
          this.getListLoading = false
        })
    },
    addHandler() {
      console.log('263editForm', this.editForm)
      let {roleName, roleDesc, appId} = this.editForm
      this.$axios({
        url: merchantRoleSave,
        method: 'post',
        data: {roleName, roleDesc, appId}
      })
        .then(res => {
          this.dialogEditVisible = false
          this.resetEditForm()
          this.getRoleList()
        })
        .finally(() => {
          this.submitBtnLoading = false
        })
    },
    editHandler() {
      let {roleName, roleDesc, id, appId} = this.editForm
      this.$axios({
        url: merchantRoleUpdate,
        method: 'post',
        data: {id, roleDesc, roleName, appId}
      })
        .then(res => {
          this.dialogEditVisible = false
          this.messageBox('修改成功！')
          this.resetEditForm()
          this.getRoleList()
        })
        .finally(() => {
          this.submitBtnLoading = false
        })
    },
    // 验证是否勾选了权限
    checkLen() {
      let flag = false
      this.$refs.tree.getCheckedKeys().length && (flag = true)
      return flag
    },
    // 设置当前角色所拥有的菜单
    assignHandler() {
      if (!this.checkLen()) {
        this.messageBox('请选择要分配的资源！', 'warning')
        return
      }
      this.getListLoading = true
      this.$axios({
        url: roleSaveRoleResourceTree,
        method: 'post',
        data: {
          resourceIds: this.insertPermissionIds,
          roleId: this.roleId,
          appId: this.appId
        }
      })
        .then(res => {
          this.dialogTreeVisible = false
          this.messageBox('分配成功！')
        })
        .finally(res => {
          this.getListLoading = false
        })
    },
    editDialogHandler() {
      let {roleName, roleDesc} = this.editForm
      if (!roleName) {
        this.messageBox('请填写完整信息！', 'warning')
        return
      }
      this.submitBtnLoading = true
      if (this.isEdit) {
        this.editHandler()
      } else {
        this.addHandler()
      }
    },
    beforeEdit(scope) {
      this.editTitle = '修改角色'
      this.isEdit = true
      let {id, roleName, roleDesc, appId} = scope.row
      this.editForm.id = id
      this.editForm.roleName = roleName
      this.editForm.appId = appId
      this.editForm.roleDesc = roleDesc
      this.dialogEditVisible = true
    },
    beforeAdd() {
      this.isEdit = false
      this.editTitle = '新增角色'
      this.dialogEditVisible = true
    },
    // 页码更改
    handleSizeChange(size) {
      this.pageSize = size
      this.getRoleList()
    },
    // 切换不一样的页面,重置一切数据
    handleCurrentChange(curPage) {
      this.curPage = curPage
      this.getRoleList()
    },
    beforeDelete(scope) {
      this.$confirmCustom({
        title: '提示'
      })
        .then(() => {
          this.delHandler(scope)
        })
        .catch(() => {})
    },
    messageBox(msg, type = 'success') {
      this.$message({
        message: msg,
        type: type
      })
    },
    resetEditForm() {
      this.editForm = {
        id: '',
        roleName: '',
        roleDesc: ''
      }
    },
    resetForm() {
      this.searchForm = {
        roleName: '',
        addDaterange: '',
        addStartTime: '',
        addEndTime: ''
      }
      this.searchForm.addDaterange = []
    },
    getSelected() {
      this.insertPermissionIds.push(...this.$refs.tree.getCheckedKeys())
      this.insertPermissionIds.push(...this.$refs.tree.getHalfCheckedKeys())
      this.assignHandler()
    }
  }
}
</script>

<style lang="less">
.channel-jurisdiction {
  .container-box {
    height: 100%;
    overflow: auto;
  }

  .el-input {
    width: 211px;
  }

  .pagination {
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    padding-right: 0;

    .el-pagination__jump {
      .el-input {
        width: 36px;
        height: 25px;
      }
    }
  }

  .el-tree {
    height: 560px;
    overflow: auto;
  }

  .edit-form {
    .el-input,
    .el-textarea {
      width: 302px;
    }
  }
}
</style>
